
from .binary import Ask,extract_first_half_image
from meta_service.tag import ArxivTag,ArxivPaper
import os
from meta_service.pdf import PDF_DUMP_DIR,IsPdfExist,TryDownloadPDF,GetPDFPath

def detect_pyfile_absdir():
    this_pyfile_abs_path = str(__file__)
    # 获取当前目录
    this_pyfile_dir = os.path.dirname(this_pyfile_abs_path)
    return this_pyfile_dir

THIS_PYFILE_ABSDIR = detect_pyfile_absdir()
CACHE_DIR = os.path.join(THIS_PYFILE_ABSDIR, "cache")
PDF_CACHE_DIR = str(PDF_DUMP_DIR)

def CheckForInstitution(entry_id:str):
    if TryDownloadPDF(entry_id,PDF_CACHE_DIR) == False:
        raise FileNotFoundError(f"PDF not found for entry_id: {entry_id}")
    pdf_path = GetPDFPath(entry_id,PDF_CACHE_DIR)
    # 1. 将 PDF 的第一页转换为图像
    # output_image_path = 'output_image.png'
    output_image_path = os.path.join(CACHE_DIR, f"{entry_id}.png")
    extract_first_half_image(pdf_path, output_image_path)
    # 2. 调用 LLM 询问机构
    # inslist = AskLLMforInstitution(output_image_path)
    inslist = Ask(output_image_path)
    inslist = list(set(inslist))
    # 3. 将机构信息写入 tag
    tagline = "<unknown>"
    if len(inslist) > 0:
        tagline = ",".join(inslist)
    tag = ArxivTag(entry_id)
    print(f"Tagging {entry_id} with institution: {tagline}")
    tag.AddTag("institution",tagline)
